package com.ooono.factorytest.items;

import static com.ooono.factorytest.model.TestItem.STATE_FAILURE;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ooono.factorytest.R;
import com.ooono.factorytest.base.BaseActivity;
import com.ooono.factorytest.utils.SPUtils;

import java.util.Objects;

public class BluetoothTestActivity extends BaseActivity {

    private static final String TAG = "BluetoothTestActivity";

    public static final String KEY = "bt";

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothStateBroadcastReceive mReceive;

    private BluetoothLeScanner scanner;

    private TextView btTestResultTv;

    private String btResult;

    private final ScanCallback mLeScanCallback = new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            if (ActivityCompat.checkSelfPermission(BluetoothTestActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            String deviceName = result.getDevice().getName();
            int rssi = result.getRssi();
            if (!TextUtils.isEmpty(deviceName)) {
                btResult += "\n Scan device : " + deviceName + ", RSSI : " + rssi;
                btTestResultTv.setText(btResult);
                btResult += "\n Test Success";
                btTestResultTv.setText(btResult);
                scanner.stopScan(mLeScanCallback);
            }
        }
    };

    @Override
    public int getTestTitle() {
        return R.string.test_item_bluetooth;
    }

    @Override
    public String getTestKey() {
        return KEY;
    }

    @Override
    public int getContentLayout() {
        return R.layout.content_bluetooth_test;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "not supported");
            SPUtils.get(this).saveData(getTestKey(), STATE_FAILURE);
            finish();
        }

        btResult = getResources().getString(R.string.bluetooth_test_prompt);
    }

    @Override
    public void initViews() {
        btTestResultTv = findViewById(R.id.tv_bt_test_result);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerBluetoothReceiver();

        if (!mBluetoothAdapter.isEnabled()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mBluetoothAdapter.enable();
        } else {
            ourBleScan();
        }
    }

    @Override
    protected void onDestroy() {
        unregisterBluetoothReceiver();
        super.onDestroy();
    }

    private void ourBleScan() {
        scanner = mBluetoothAdapter.getBluetoothLeScanner();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请定位授权
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        } else {
            scanner.startScan(mLeScanCallback);
        }
    }

    public void registerBluetoothReceiver() {
        if (mReceive == null) {
            mReceive = new BluetoothStateBroadcastReceive();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mReceive, intentFilter);
    }

    public void unregisterBluetoothReceiver() {
        if (mReceive != null) {
            unregisterReceiver(mReceive);
            mReceive = null;
        }
    }

    class BluetoothStateBroadcastReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Objects.requireNonNull(action).equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                if (blueState == BluetoothAdapter.STATE_ON) {
                    Toast.makeText(context, "蓝牙已开启", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "onReceive: " + "蓝牙已开启:");
                    ourBleScan();
                }
            }
        }
    }

}